#pragma once 
#include <cstdint>
#include <string>
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Commn.hpp"
#include <cstring>
class InetAddr
{
public:
    InetAddr(sockaddr_in& addr)
        :_net_addr(addr)
    {
        Net2HostIp();
        Net2HostPort();
    }
    void Net2HostIp()
    {
        char Ip[1024];
        memset(Ip,0,sizeof(Ip));
        //::inet_ntop(AF_INET,&(_net_addr.sin_addr),Ip,sizeof(Ip)); //把网络ip地址转为点分十进制 192.132.168.10
        if(::inet_ntop(AF_INET,&(_net_addr.sin_addr),Ip,sizeof(Ip)) == nullptr){
	    perror("inet_ntop failed");
	    _ip = "InvalidIP";
	}else{
            _ip = Ip;
	}
    }
    
    void Net2HostPort()
    {
        _port = ::ntohs(_net_addr.sin_port);
    }

    InetAddr(uint16_t port)
        :_port(port)
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = ::htons(_port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }

    sockaddr* NetAddr()
    {
        return (sockaddr*)(&_net_addr);
    }

    socklen_t Len() { return sizeof(_net_addr);}
    
    std::string IP() {return _ip;}
    uint16_t Port() { return _port;}

    std::string netaddr() { 
        std::string Ip = _ip;
        std::cout << "Ip: " << _ip << std::endl;
        std::string pp = std::to_string(_port);
        std::string ans = Ip + pp;
        return ans;
    }
private:
    uint16_t _port;
    std::string _ip = "";
    sockaddr_in _net_addr;
};
